package com.linsir.core;

import com.linsir.lin.pojo.Account;
import com.linsir.lin.pojo.Permission;
import com.linsir.lin.service.impl.AccountServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName:linsir-lin
 * @Package:com.linsir.core
 * @Title: ShiroRealm
 * @Description: TODO
 * @Create:2021/6/9 23:27 by @author:Linsir
 * @Update:2021/6/9 23:27 by @author:Linsir
 * @UpdateRemark: 初始创建
 * @Version 1.0.0
 */
@Slf4j
@Component
public class ShiroRealm  extends AuthorizingRealm {

    @Resource
    private AccountServiceImpl accountService;

    /*@Resource
    private RolePermissonService rolePermissonService;*/

    /***
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户
        Account account= (Account) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String > roles = accountService.roleStrs(account);
        List<Permission> permissionList= accountService.getPerminssionByAccount(account);
        Set<String>  permissionStr= accountService.perminssionStrs(permissionList);

        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissionStr);
        return info;
    }

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
           Account account = new Account();
           String loginName = (String) authenticationToken.getPrincipal();
           account=accountService.getByUserName(loginName);
           if (account==null)
           {
                log.info("用户不存在! 登录名:{}, 密码:{}",loginName,authenticationToken.getCredentials());
                return null;
           }
           SimpleAuthenticationInfo authenticationInfo =new SimpleAuthenticationInfo(account,account.getPassword(), ByteSource.Util.bytes(account.getUserName()),getName());
           return  authenticationInfo;
    }
}
